package com.jy.adscm.wechat.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.jy.adscm.exception.AdscmSystemException;
import com.jy.adscm.utils.AdscmBaseUtils;
import com.jy.adscm.wechat.bean.*;
import com.jy.adscm.wechat.mapper.mysql.WechatPartsDetailMapper;
import com.jy.adscm.wechat.mapper.mysql.WechatUserMapper;
import com.jy.adscm.wechat.service.WechatPartsDetailService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.jy.adscm.wechat.service.WechatPartsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zyl
 * @since 2019-09-30
 */
@Service
public class WechatPartsDetailServiceImpl extends ServiceImpl<WechatPartsDetailMapper, WechatPartsDetail> implements WechatPartsDetailService {
    @Autowired
    WechatUserMapper wechatUserMapper;
    @Autowired
    WechatPartsService wechatPartsService;
    @Override
    public Boolean insertWechatPartsDetail(WechatPartsDetail wechatPartsDetail, String openid) throws AdscmSystemException{
        WechatUser wechatUser = wechatUserMapper.selectByOpenId(openid);
        if (!AdscmBaseUtils.getInstance().isNotEmpty(wechatUser,null)){
            throw new AdscmSystemException("不存在该用户");
        }
        wechatPartsDetail.setOutStocker(wechatUser.getId().toString());
        wechatPartsDetail.setOutStockTime(new Date());
        wechatPartsDetail.setNums(1f);
        boolean insert = super.insert(wechatPartsDetail);
        //扣减任务中的数量
        WechatParts WechatParts=    wechatPartsService.updateWechatPartsVaule(wechatPartsDetail.getPid(),wechatPartsDetail.getNums());


        return true;
    }

    @Override
    public List<WechatPartsDetail> selectByPid(Long pid) {
        Wrapper<WechatPartsDetail> wechatPartsDetailWrapper=new EntityWrapper<>();
        wechatPartsDetailWrapper.eq("pid",pid);
        List<WechatPartsDetail> wechatPartsDetails = super.selectList(wechatPartsDetailWrapper);
        for (WechatPartsDetail wechatPartsDetail : wechatPartsDetails) {
            if (AdscmBaseUtils.getInstance().isNotEmpty(wechatPartsDetail.getOutStocker(),null)){
                WechatUser wechatUser = wechatUserMapper.selectById(wechatPartsDetail.getOutStocker());
                wechatPartsDetail.setOutStocker(wechatUser.getName());
            }
        }
        return wechatPartsDetails;
    }

    @Override
    public WechatPartsDetail selectWechatPartsDetailById(Long id) {
        WechatPartsDetail wechatPartsDetail = super.selectById(id);
        if (AdscmBaseUtils.getInstance().isNotEmpty(wechatPartsDetail.getOutStocker(),null)){
            WechatUser wechatUser = wechatUserMapper.selectById(wechatPartsDetail.getOutStocker());
            wechatPartsDetail.setOutStocker(wechatUser.getName());
        }
        return wechatPartsDetail;
    }
}
